package rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("101.42.44.62");  // 主机
        factory.setPort(5672);            // 端口号
        factory.setUsername("rht");       // 账号
        factory.setPassword("47298");     // 密码
        factory.setVirtualHost("test");   // 虚拟主机
        Connection connection = factory.newConnection();
        // 2. 开启通道
        Channel channel = connection.createChannel();
        // 3. 声明交换机, 此处使用内置的交换机

        // 4. 声明队列
        /**
         * queueDeclare(String queue 队列名称,
         *      boolean durable 是否可持久化,
         *      boolean exclusive 该队列是否被独占,
         *      boolean autoDelete 该队列没有消费者时 是否自动删除,
         *      Map<String, Object> arguments 参数) throws IOException
         */
        channel.queueDeclare("test", true, false, false, null);
        // 5. 发送消息
        /**
         * basicPublish(String exchange 交换机名称,
         *      String routingKey 内置交换机 队列名,
         *      BasicProperties props 属性配置,
         *      byte[] body 消息)
         */
        String message = "hello rabbitmq";
        channel.basicPublish("", "test", null, message.getBytes());
        System.out.println("消息发送成功");
        // 6. 资源释放
        channel.close();
        connection.close();
    }
}
